<template>
  <div class="oe-grade-manage" v-loading="loading">
    <top-tip :examTitle="examTitle" :batchTitle="batchTitle" :teacherName="teacherName" :showBack="true"></top-tip>
    <div class="oe-grade-contain">
      <div class="oe-manage-search">
        <span class="oe-manage-text">姓名/学号：</span>
        <span class="oe-manage-input">
          <a-input placeholder="请输入姓名/学号" v-model="key" />
        </span>
        <span class="oe-manage-text">请选择班级：</span>
        <a-select
          showSearch
          :value="classes"
          allowClear
          placeholder="请选择班级"
          style="width: 200px"
          :defaultActiveFirstOption="false"
          :filterOption="false"
          @search="handleClassSearch"
          @change="handleClassChange"
          @focus="getClassList('')"
          :notFoundContent="classLoading ? undefined : '无数据'"
        >
          <a-spin v-if="classLoading" slot="notFoundContent" size="small" />
          <a-select-option v-for="d in classList" :key="d.id">{{ d.text }}</a-select-option>
        </a-select>
        <span class="oe-manage-btns">
          <a-button type="primary" @click.stop="getMonitorStuList">查询</a-button>
          <a-button type="primary" @click="showModal" v-if="operationList.includes('add/edit/del:monitor')">导入监考学生</a-button>
          <a-button type="primary" @click="deletedAll" v-if="operationList.includes('add/edit/del:monitor')">批量删除</a-button>
        </span>
      </div>
      <a-modal
        title="导入监考学生"
        class="oe-student"
        :visible="imported"
        width="80%"
        @cancel="importedCancel"
        :afterClose="afterClose"
      >
        <div class="oe-modal-one">
          <a-select
            showSearch
            :value="factory"
            placeholder="请选择院系"
            style="width: 200px"
            allowClear
            :defaultActiveFirstOption="false"
            :filterOption="false"
            @search="handleFactorySearch"
            @change="handleFactoryChange"
            @focus="getFactoryList('')"
            :notFoundContent="factoryLoading ? undefined : '无数据'"
          >
            <a-spin v-if="factoryLoading" slot="notFoundContent" size="small" />
            <a-select-option v-for="d in factoryList" :key="d.id">{{ d.text }}</a-select-option>
          </a-select>
          <a-select
            showSearch
            :value="grade"
            allowClear
            placeholder="请选择年级"
            style="width: 200px"
            :defaultActiveFirstOption="false"
            :filterOption="false"
            @search="handleGradeSearch"
            @change="handleGradeChange"
            @focus="getGradeList('')"
            :notFoundContent="gradeLoading ? undefined : '无数据'"
          >
            <a-spin v-if="factoryLoading" slot="notFoundContent" size="small" />
            <a-select-option v-for="d in gradeList" :key="d.id">{{ d.text }}</a-select-option>
          </a-select>
          <a-select
            showSearch
            :value="classes"
            allowClear
            placeholder="请选择班级"
            style="width: 200px"
            :defaultActiveFirstOption="false"
            :filterOption="false"
            @search="handleClassSearch"
            @change="handleClassChange"
            @focus="getClassList('')"
            :notFoundContent="classLoading ? undefined : '无数据'"
          >
            <a-spin v-if="classLoading" slot="notFoundContent" size="small" />
            <a-select-option v-for="d in classList" :key="d.id">{{ d.text }}</a-select-option>
          </a-select>
          <span class="oe-select-input">
            <a-input placeholder="请输入姓名/学号" v-model="keyZjy" />
          </span>
          <a-button type="primary" @click.stop="getImportList">查询</a-button>
        </div>
        <div class="oe-select-table">
          <a-table
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectStu }"
            :columns="importedColumns"
            :dataSource="importedDatas"
            :pagination="paginationZjy"
            @change="onZjyTableChange"
          >
          </a-table>
        </div>
        <template slot="footer">
          <a-button @click="importedSure" type="primary" html-type="submit">
            确定
          </a-button>
          <a-button @click.stop="importedCancel">
            取消
          </a-button>
        </template>
      </a-modal>
      <div class="oe-manage-content">
        <a-table
          :rowSelection="{ selectedRowKeys: selectedStudent, onChange: onSelectStudent }"
          :columns="columns"
          :dataSource="datas"
          :pagination="pagination"
          @change="onTableChange"
        >
          <span slot="action" slot-scope="text, record">
            <a-tooltip placement="bottom" title="删除" v-if="operationList.includes('add/edit/del:monitor')">
              <span @click="deleted(record)" class="action-icon"><i class="iconfont icon-delete"></i></span>
            </a-tooltip>
          </span>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
import GetOperationList from '@/lib/mixin/methods.js';
export default {
  mixins: [GetOperationList],
  components: {
    topTip
  },
  data() {
    return {
      titleText: '',
      imported: false,
      key: '',
      keyZjy: '',
      lookItem: [],
      selectType: [],
      idsStuIds: [],
      idstudents: [],
      importedColumns: [
        {
          title: '序号',
          dataIndex: 'Number',
          align: 'center'
        },
        {
          title: '姓名',
          dataIndex: 'DisplayName',
          sorter: true,
          align: 'center'
        },
        {
          title: '学号',
          dataIndex: 'UserNo',
          sorter: true,
          align: 'center'
        },
        {
          title: '用户名',
          dataIndex: 'UserName',
          sorter: true,
          align: 'center'
        },
        {
          title: '院系',
          dataIndex: 'SubName',
          sorter: true,
          align: 'center',
          key: 'SubName'
        },
        {
          title: '专业',
          dataIndex: 'MajorName',
          sorter: true,
          align: 'center',
          key: 'MajorName'
        },
        {
          title: '年级',
          dataIndex: 'GradeName',
          sorter: true,
          align: 'center',
          key: 'GradeName'
        },
        {
          title: '班级',
          dataIndex: 'ClassName',
          sorter: true,
          align: 'center',
          key: 'ClassName'
        }
      ],
      importedDatas: [],
      //新增
      add: false,
      loading: false,
      paginationZjy: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showQuickJumper: false,
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.paginationZjy.current = current;
          this.paginationZjy.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          // this.getExamList(current, pageSize);
          this.paginationZjy.current = current;
          this.paginationZjy.pageSize = pageSize;
        },
        buildOptionText(props) {
          // console.log(props);
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      // 分页配置
      pagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          // this.getExamList(current, pageSize);
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          // console.log(props);
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      //年级管理
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      selectedRowKeys: [],
      selectedStudent: [],
      factoryLoading: false,
      gradeLoading: false,
      classLoading: false,
      // 院系列表
      factoryList: [],
      // 年级列表
      gradeList: [],
      // 班级列表
      classList: [],
      // 选择的院系
      factory: undefined,
      // 班级
      classes: undefined,
      // 年级
      grade: undefined,
      datas: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'Number',
          align: 'center'
        },
        {
          title: '姓名',
          dataIndex: 'DisplayName',
          sorter: true,
          align: 'center'
        },
        {
          title: '学号',
          dataIndex: 'UserNo',
          sorter: true,
          align: 'center'
        },
        {
          title: '用户名',
          dataIndex: 'UserName',
          sorter: true,
          align: 'center'
        },
        {
          title: '院系',
          dataIndex: 'SubName',
          sorter: true,
          align: 'center',
          key: 'SubName'
        },
        {
          title: '专业',
          dataIndex: 'MajorName',
          sorter: true,
          align: 'center',
          key: 'MajorName'
        },
        {
          title: '年级',
          dataIndex: 'GradeName',
          sorter: true,
          align: 'center',
          key: 'GradeName'
        },
        {
          title: '班级',
          dataIndex: 'ClassName',
          sorter: true,
          align: 'center',
          key: 'ClassName'
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      // 操作List
      operationList: [],
      IsOpList: [],
      examTitle:'',
      batchTitle:'',
      teacherName:'',
    };
  },
  computed: {
    examid() {
      return this.$route.params.examid;
    },
    teacherkey() {
      return this.$route.params.teacherkey;
    },
    teacherid() {
      return this.$route.params.teacherid;
    },
    examType() {
      return this.$route.params.examType;
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.getOpeartion();
      vm.getDataList()
    });
  },
  methods: {
    getDataList() {
      this.loading = true;
      this.$http
        .post('/api/SchoolManager/teacher/getTeacherList', {
          key: this.teacherkey
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code > 0) {
            this.teacherName = rst.list[0].DisPlayName
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 判断是否是只读
    getIsWrite(type) {
      type = "add/edit/del:monitor";
      let index = this.IsOpList.findIndex((el) => {
        return el.Name === type;
      });
      if (index > -1) {
        if (this.IsOpList[index].IsRead && !this.IsOpList[index].IsWrite) {
          this.$message.info('您没有该操作权限！');
          return false;
        } else {
          return true;
        }
      }
    },
    // 点击table排序
    onTableChange(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getMonitorStuList(pagenation.current, pagenation.pageSize, sortOrder);
    },
    // 获取页面操作
    getOpeartion() {
      this.loading = true;
      this.GetOperationList('examId',this.examid).then((rst) => {
        this.loading = false;
        this.loading = false;
        this.operationList = [];
        this.IsOpList = [];
        if (rst.code === 1) {
          if (rst.list.length) {
            rst.list.forEach((item) => {
              if(item.IsWrite){
              this.operationList.push(item.Name);
              }
              this.IsOpList = rst.list;
            });
            // this.operationList = rst.list;
          }
          this.examTitle = rst.examTitle
          this.batchTitle = rst.batchTitle
          this.getMonitorStuList();
        } else {
          this.$message.error(rst.msg);
        }
      });
    },
    //获取班级数据
    getMonitorStuList(page, pageSize, sortOrder) {
      this.loading = true;
      this.$http
        .post('/api/examMonitor/ExamMonitorStu/getMonitorStuList', {
          examId: this.examid,
          teacherId: this.teacherid,
          examType: this.examType,
          key: this.key,
          classId: this.classes || '',
          sort: sortOrder || '',
          page: page || 1,
          pageSize: pageSize || 10
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code > 0) {
            this.datas = [];
            this.pagination.current = rst.pagination.pageIndex;
            this.pagination.pageSize = rst.pagination.pageSize;
            this.pagination.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.datas.push({
                  ...item,
                  Number: number
                });
              });
            }
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    //删除
    deleted(value) {
      if (!this.getIsWrite('删除')) {
        return;
      }
      this.$confirm({
        title: '提示',
        content: '确认移除选择的数据吗？',
        centered: true,
        onOk: () => {
          this.$http
            .post('/api/examMonitor/ExamMonitorStu/deleteMonitorStu', {
              ids: value.Id, //要删除的成员id数组
              examType: this.examType,
              examId: this.examid,
              teacherId: this.teacherid 
            })
            .then((res) => {
              if (res.code > 0) {
                this.$message.success(res.msg);
                this.getMonitorStuList();
                this.selectedStudent = [];
              } else {
                this.$message.error(res.msg);
              }
            });
        },
        onCancel() {}
      });
    },
    deletedAll() {
      if (!this.getIsWrite('删除')) {
        return;
      }
      if (this.idstudents.length == 0) {
        this.$message.error('请勾选需要移除的监考学生！');
        return;
      }
      this.$confirm({
        title: '提示',
        content: '确认批量移除选择的数据吗？',
        centered: true,
        onOk: () => {
          this.$http
            .post('/api/examMonitor/ExamMonitorStu/deleteMonitorStu', {
              ids: this.idstudents, //要删除的成员id数组
              examType: this.examType,
              examId: this.examid,
              teacherId: this.teacherid 
            })
            .then((res) => {
              if (res.code > 0) {
                this.$message.success(res.msg);
                this.getMonitorStuList();
                this.selectedStudent = [];
              } else {
                this.$message.error(res.msg);
              }
            });
        },
        onCancel() {}
      });
    },
    //导入
    showModal() {
      this.keyZjy = '';
      this.factory = undefined;
      this.grade = undefined;
      this.classes = undefined;
      this.imported = true;
      this.getImportList();
    },
    // 点击table排序
    onZjyTableChange(paginationZjy, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getImportList(paginationZjy.current, paginationZjy.pageSize, sortOrder);
    },
    getImportList(page, pageSize, sortOrder) {
      this.loading = true;
      this.$http
        .post('/api/examMonitor/ExamMonitorStu/getImportList', {
          examId: this.examid,
          key: this.keyZjy,
          examType: this.examType,
          sort: sortOrder || '',
          subId: this.factory || '',
          gradeId: this.grade || '',
          classId: this.classes || '',
          page: page || 1,
          pageSize: pageSize || 10
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code == 1) {
            this.selectedRowKeys = [];
            this.idsStuIds = [];
            this.importedDatas = [];
            this.paginationZjy.current = rst.pagination.pageIndex;
            this.paginationZjy.pageSize = rst.pagination.pageSize;
            this.paginationZjy.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.importedDatas.push({
                  ...item,
                  Number: number
                });
              });
            }
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    importedCancel() {
      this.imported = false;
      this.keyZjy = '';
      this.factory = undefined;
      this.grade = undefined;
      this.classes = undefined;
    },
    importedSure() {
      if (!this.getIsWrite('新增')) {
        return;
      }
      if (this.idsStuIds.length == 0) {
        this.$message.error('请勾选监考学生！');
        return;
      }
      this.$http
        .post('/api/examMonitor/ExamMonitorStu/saveExamMonitorStu', {
          ids: this.idsStuIds,
          examId: this.examid,
          teacherId: this.teacherid,
          examType: this.examType
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code > 0) {
            this.$message.success(rst.msg);
            this.idsStuIds = [];
            this.selectedRowKeys = [];
            this.imported = false;
            this.getMonitorStuList();
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    //多选
    onSelectStu(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      var ids = [];
      for (let i = 0; i < selectedRows.length; i++) {
        ids.push(selectedRows[i].Id);
      }
      this.idsStuIds = ids;
    },
    //列表多选
    onSelectStudent(selectedRowKeys, selectedRows) {
      this.selectedStudent = selectedRowKeys;
      var ids = [];
      for (let i = 0; i < selectedRows.length; i++) {
        ids.push(selectedRows[i].Id);
      }
      this.idstudents = ids;
    },
    // 院系搜索
    handleFactorySearch(val) {
      this.getFactoryList(val, this.school);
    },
    // 获取院系列表
    getFactoryList(search) {
      this.factoryLoading = true;
      this.$http
        .post('/api/common/localstorage/getESSubList', {
          q: search
        })
        .then((rst) => {
          this.factoryLoading = false;
          if (rst.code == 1) {
            this.factoryList = rst.list;
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 获取年级列表
    getGradeList(search) {
      this.gradeLoading = true;
      this.$http
        .post('/api/common/localstorage/getESGradeList', {
          q: search
        })
        .then((rst) => {
          this.gradeLoading = false;
          if (rst.code == 1) {
            this.gradeList = rst.list;
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 获取班级列表
    getClassList(search) {
      this.classLoading = true;
      this.$http
        .post('/api/common/localstorage/getESClassList', {
          q: search
        })
        .then((rst) => {
          this.classLoading = false;
          if (rst.code == 1) {
            this.classList = rst.list;
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 改变选择的院系
    handleFactoryChange(val) {
      this.factory = val;
    },
    // 年级搜索
    handleGradeSearch(val) {
      this.getGradeList(val, this.school);
    },
    // 改变选择的年级
    handleGradeChange(val) {
      this.grade = val;
    },
    // 班级搜索
    handleClassSearch(val) {
      this.getClassList(val, this.school);
    },
    // 改变选择的班级
    handleClassChange(val) {
      this.classes = val;
    },
    // 按照条件查询
    searchList() {
      console.log(this.examName, this.selectType);
    },
    // 导入职教云关闭后的回调
    afterClose() {
      this.selectedRowKeys = [];
      this.idsStuIds = [];
      this.keyZjy = '';
    }
  }
};
</script>

<style></style>
